export const cloneOf = (obj) => {
    return JSON.parse(JSON.stringify(obj));
};

export const getUrlParamter = (url) => {
    let vars = {};
    url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[ key ] = value;
    });
    return vars;
};

export const queryOf = (obj) => {
    let str = '';
    for (let key in obj) {
        let val = obj[ key ];
        if (val === undefined)
            continue;

        str += key + '=' + val + '&';
    }
    return str;
};

export const readerImage = (file, cb) => {
    if (!file || !cb) {
        return;
    }
    var reader = new FileReader();

    reader.onloadend = function () {
        if (typeof cb === 'function') {
            cb(reader);
        }
    };
    reader.readAsDataURL(file)
};

export const pushHistory = () => {
    let state = {
        title: '',
        url  : ''
    };
    window.history.pushState(state, state.title, state.url)
};

/**
 * 解析方法字符串
 * @param string {String} 方法字符串
 * @returns {{method: *, params: Array}}
 */
export const parseStringMethod = (string) => {
    let arr = string.split(':');

    let method = arr[ 0 ];
    let params = [];
    if (arr[ 1 ]) {
        params = arr[ 1 ].split("|");
    }

    return {
        method,
        params
    }
};

export const shuffleArray = (array) => {
    let currentIndex = array.length,
        temporaryValue,
        randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue        = array[ currentIndex ];
        array[ currentIndex ] = array[ randomIndex ];
        array[ randomIndex ]  = temporaryValue;
    }

    return array;
};

export const oneOf = (arr, val) => {
    return arr.includes(val);
};

export const randomNum = (max, min = 0) => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

export const elementOffset = (el) => {
    let itemEl = $(el);
    return {
        ...itemEl.offset(),
        height: itemEl.outerHeight(),
        width : itemEl.outerWidth()
    };
}

export const addImageProcess = (src) => {
    return new Promise((resolve, reject) => {
        let img     = new Image();
        img.onload  = () => resolve(img.height);
        img.onerror = reject;
        img.src     = src
    })
};

export const kstTypeUrl = (option) => {
    if (typeof option === 'string') {
        let item = CONFIG.TYPE_OPTIONS[ option ];
        if (!item) {
            throw new TypeError('Type Option not Exists.');
        }

        option = item;
    }

    return `${ option.domain }bs/im.htm?cas=${ option.cas }___${ option.id }&fi=${ option.fi }`;
}

export const getOptionForType = (type) => {
    console.log('type :', type);
    return CONFIG.TYPE_OPTIONS[ type ];
}

export const validationType = (type) => {
    return !!getOptionForType(type);
}


export const loadJS = (url, implementationCode, location) => {
    implementationCode = typeof implementationCode === 'function' ? implementationCode : function () {
    };
    location           = location || document.body;
    //url is URL of external file, implementationCode is the code
    //to be called from the file, location is the location to
    //insert the <script> element

    let scriptTag = document.createElement('script');
    scriptTag.src = url;

    scriptTag.onload             = implementationCode;
    scriptTag.onreadystatechange = implementationCode;

    location.appendChild(scriptTag);
};


export const getPageRefer = () => {
    if (document.referrer) {
        try {
            var refer = document.referrer;

            if (refer) {
                var referDomain = jesongGetDomain(refer);
                var currDomain  = window.location.host;
                if (referDomain && referDomain == currDomain) {
                    refer = "";
                }
            }

            if (refer != "") {
                return refer;
            }
        } catch (e) {
        }
        ;
    }
    return "";
}


const baseRepeatKey          = {
    name : '姓名',
    phone: '电话'
};
export const paramsToMessage = (data) => {
    let resultArr = [];

    for (let [ key, value ] of Object.entries(data)) {
        if (baseRepeatKey[ key ]) {
            key = baseRepeatKey[ key ];
        }
        resultArr.push(`${ key }: ${ value }`);
    }

    return "####" + resultArr.join('<br/>');
}

export const getChannel = () => {
    var url_string = window.location.href;
    var url        = new URL(url_string);
    return (url.searchParams.get("channel") || CONFIG.BASE.CHANNEL);
};

export const objIsEmpty = (obj) => {

    // null and undefined are "empty"
    if (obj == null) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length > 0) return false;
    if (obj.length === 0) return true;

    // If it isn't an object at this point
    // it is empty, but it can't be anything *but* empty
    // Is it empty?  Depends on your application.
    if (typeof obj !== "object") return true;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and valueOf enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

export const sleep = (time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
}
